package config

import (
	"encoding/json"
	"fmt"
	"github.com/pkg/errors"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"os"
	"strings"
	"xj.com/oos-naming-service/error_handler"
)

type serverConfig struct {
	Host string
	Port int
}

type esConfig struct {
	Url string
}

type logConfig struct {
	FileName string
	Level    log.Level
}

type Node struct {
	Ip     string
	OnLine bool
}

type data struct {
	Nodes    []Node
	MinNodes int
}

type SysConfig struct {
	Data   data
	Es     esConfig
	Log    logConfig
	Server serverConfig
}

type PlainFormatter struct {
	TimestampFormat string
}

const (
	NestDateTimeFormat = "2006-01-02T15:04:05.000" //与ES保持一致
)

var Config SysConfig

func init() {
	//初始化日志格式，配置
	plainFormatter := new(PlainFormatter)
	plainFormatter.TimestampFormat = NestDateTimeFormat
	log.SetFormatter(plainFormatter)

	viper.SetConfigName("config")
	viper.AddConfigPath(".")
	viper.AutomaticEnv()
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))

	err := viper.ReadInConfig()
	error_handler.ExitWenError(errors.WithMessage(err, "读取配置文件信息出错。"))

	err = viper.Unmarshal(&Config)
	error_handler.ExitWenError(errors.WithMessage(err, "解析配置文件内容出错。"))

	//打印日志，方便观察
	jsonStr, _ := json.Marshal(Config)
	log.Info("服务器配置：", string(jsonStr))

	initLog()
}

func (f *PlainFormatter) Format(entry *log.Entry) ([]byte, error) {
	timestamp := fmt.Sprintf(entry.Time.Format(f.TimestampFormat))
	return []byte(fmt.Sprintf("%s %s : %s\n", timestamp, entry.Level, entry.Message)), nil
}

func initLog() {
	if len(Config.Log.FileName) == 0 {
		//标准输出方式打印日志
		log.SetOutput(os.Stdout)
	} else {
		//以文件方式打印日志
		file, err := os.OpenFile(Config.Log.FileName, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
		error_handler.ExitWenError(err)

		log.SetOutput(file)
	}
	log.SetLevel(Config.Log.Level)
}
